<template>
  <div class="container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>试题录入</span>
      </div>
      <section>
        <el-form ref="form" :rules="rules" :model="form" label-width="120px">
          <el-form-item label="学科:" prop="subjectID">
            <el-select
              @change="subjectsChange"
              style="width:400px"
              v-model="form.subjectID"
              placeholder="请选择"
            >
              <el-option
                v-for="item in subjects"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="目录:" prop="catalogID">
            <el-select style="width:400px" v-model="form.catalogID" placeholder="请选择">
              <el-option
                v-for="item in directorys"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="企业:" prop="enterpriseID">
            <el-select style="width:400px" v-model="form.enterpriseID" placeholder="请选择">
              <el-option
                v-for="(item, index) in companys"
                :key="index"
                :label="item.shortName"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="城市:" prop="city">
            <el-col :span="4" style="margin-right:14px">
              <el-select @change="provincesChange" v-model="form.province" placeholder="请选择">
                <el-option
                  v-for="(item, index) in provinces"
                  :key="index"
                  :label="item"
                  :value="item"
                ></el-option>
              </el-select>
            </el-col>
            <el-col :span="4">
              <el-select v-model="form.city" placeholder="请选择">
                <el-option v-for="(item, index) in citys" :key="index" :label="item" :value="item"></el-option>
              </el-select>
            </el-col>
          </el-form-item>
          <el-form-item label="方向:" prop="direction">
            <el-select style="width:400px" v-model="form.direction" placeholder="请选择">
              <el-option v-for="(item, index) in direction" :key="index" :label="item" value="item"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="题型:" prop="questionType">
            <el-radio-group @input="questionTypeInput" v-model="form.questionType">
              <el-radio
                v-for="item in questionTypeList"
                :key="item.value"
                :label="String(item.value)"
              >{{ item.label }}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="难度:" prop="difficulty">
            <el-radio-group v-model="form.difficulty">
              <el-radio
                v-for="item in difficultyList"
                :key="item.value"
                :label="String(item.value)"
              >{{ item.label }}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="题干:" prop="question">
            <quill-editor v-model="form.question" ref="myQuillEditor" :options="editorOption"></quill-editor>
          </el-form-item>
          <el-form-item v-if="!(form.questionType === '3')" label="选项:">
            <div style="line-height:60px" v-for="(item,index) in form.options" :key="index">
              <!-- 单选选项的选项 -->
              <el-radio
                v-if="form.questionType === '1'"
                v-model="item.isRight"
                @change="radioChange(item)"
                :label="1"
              >{{item.code}}:</el-radio>
              <!-- 多选选项的选项 -->
              <el-checkbox
                v-if="form.questionType === '2'"
                v-model="item.isRight"
                :label="1"
              >{{item.code}}</el-checkbox>
              <el-input style="margin:5px;width:400px" v-model="item.title"></el-input>
              <el-upload
                action
                style="display: inline"
                list-type="picture-card"
                :file-list="item.fileList"
                :http-request="file=>httpRequest(file,index)"
                :before-upload="beforeAvatarUpload"
                :on-change="(file, fileList)=>onChange(file, fileList, index)"
                :on-remove="(file, fileList)=>onRemove(file, fileList, index)"
              >
                <i class="imageText">上传图片</i>
                <i class="el-icon-close icon-close" style></i>
              </el-upload>
              <el-button
                type="danger"
                style="margin-left:10px"
                @click="delQuestionType(index)"
                v-if="form.questionType === '2'"
                icon="el-icon-delete"
                circle
              ></el-button>
            </div>

            <el-form-item>
              <el-button
                type="danger"
                size="mini"
                @click="addQuestionType"
                :disabled="!(form.questionType === '2')"
              >+增加选项与答案</el-button>
            </el-form-item>
          </el-form-item>
          <el-form-item label="解析视频:">
            <el-input style="width:400px" v-model="form.videoURL"></el-input>
          </el-form-item>
          <el-form-item label="答案解析:" prop="answer">
            <quill-editor v-model="form.answer" ref="myQuillEditor" :options="editorOption"></quill-editor>
          </el-form-item>
          <el-form-item label="题目备注:">
            <el-input type="textarea" v-model="form.remarks"></el-input>
          </el-form-item>
          <el-form-item label="试题标签:">
            <el-select
              multiple
              filterable
              remote
              allow-create
              style="width:400px"
              v-model="form.tags"
              placeholder="请选择试题标签"
            >
              <el-option
                v-for="item in tags"
                :key="item.value"
                :label="item.label"
                :value="item.label"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button v-if="!($route.query.id)" type="primary" @click="submitForm">确认提交</el-button>
            <el-button v-else type="success" @click="submitForm">确认修改</el-button>
          </el-form-item>
        </el-form>
      </section>
    </el-card>
  </div>
</template>

<script>
import { simple as subjectsList } from '@/api/hmmm/subjects'
import { simple as tagsList } from '@/api/hmmm/tags'
import { simple as directorysList } from '@/api/hmmm/directorys'
import { list as companysList } from '@/api/hmmm/companys'
import { provinces as provincesList, citys as citysList } from '@/api/hmmm/citys'
import { add as questionsAdd, detail as detailList, update } from '@/api/hmmm/questions'
import { direction as directionList, difficulty as difficultyList, questionType as questionTypeList } from '@/api/hmmm/constants'
const newOptions = () => {
  return [
    { isRight: 0, code: 'A', title: '', img: '', fileList: [] },
    { isRight: 0, code: 'B', title: '', img: '', fileList: [] },
    { isRight: 0, code: 'C', title: '', img: '', fileList: [] },
    { isRight: 0, code: 'D', title: '', img: '', fileList: [] }
  ]
}
// 工具栏配置
const toolbarOptions = [
  ['bold', 'italic', 'underline', 'strike'], // 加粗 斜体 下划线 删除线
  [{ list: 'ordered' }, { list: 'bullet' }],
  ['blockquote'],
  ['code-block', 'image', 'link'] // 链接、图片、视频
]
// 腾讯云
var COS = require('cos-js-sdk-v5')

// SECRETID 和 SECRETKEY 请登录 https://console.cloud.tencent.com/cam/capi 进行查看和管理
var cos = new COS({
  SecretId: 'AKIDwhGpH8vX6b3NWYUOFvWyEG7KOCe1DAtt',
  SecretKey: '2saDoLrGk8RXQHF6ygCh5KPL8sV9hEjJ'
})

export default {
  data () {
    return {
      form: {
        subjectID: '', // 学科
        catalogID: '', // 目录
        enterpriseID: '', // 企业
        province: '', // 城市
        city: '', // 地区
        direction: '', // 方向
        questionType: '1', // 题型
        difficulty: '1', // 难度
        question: '', // 题干
        options: newOptions(), // 选项
        videoURL: '', // 解析视频
        answer: '', // 答案解析
        remarks: '', // 题目备注
        tags: '' // 试题标签

      },
      subjects: [], // 学科列表
      tags: [], // 标签选择框
      directorys: [], // 目录列表
      companys: [], // 企业
      provinces: provincesList(), // 城市列表
      citys: [], // 地区列表
      direction: [...directionList], // f方向
      difficultyList,
      questionTypeList,
      // 富文本框配置内容
      editorOption: {
        placeholder: '',
        modules: {
          toolbar: {
            container: toolbarOptions
          }
        }
      },
      // 校验规则
      rules: {
        subjectID: [
          { required: true, message: '请输入学科', trigger: 'change' }
        ],
        catalogID: [
          { required: true, message: '请输入目录', trigger: 'change' }
        ],
        enterpriseID: [
          { required: true, message: '请输入企业', trigger: 'change' }
        ],
        city: [
          { required: true, message: '请输入城市', trigger: 'change' }
        ],
        direction: [
          { required: true, message: '请输入方向', trigger: 'change' }
        ],
        questionType: [
          { required: true, message: '请输入题型', trigger: 'blur' }
        ],
        difficulty: [
          { required: true, message: '请输入难度', trigger: 'blur' }
        ],
        question: [
          { required: true, message: '请输入题干', trigger: 'blur' }
        ],
        answer: [
          { required: true, message: '请输入答案', trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    // 获取学科列表
    this.subjectsList()
    // 获取企业
    this.companysList()
    // 判断是别的编辑跳过来的吗
    if (this.$route.query?.id) {
      // 详情回显
      this.detailList()
    }
  },
  methods: {
    // 单选框改变后
    radioChange (item) {
      this.form.options.forEach(item => {
        item.isRight = 0
      })
      item.isRight = 1
    },
    // 获取学科列表
    async subjectsList () {
      const res = await subjectsList()
      // console.log(res)
      this.subjects = res.data
    },
    // 学科选中后的钩子
    subjectsChange (subjectID) {
      // console.log(value)
      this.tagsList(subjectID)
      this.directorysList(subjectID)
    },
    // 获取简单标签列表
    async tagsList (subjectID) {
      const res = await tagsList({ subjectID })
      // console.log(res)
      this.tags = res.data
    },
    // 获取简单目录列表
    async directorysList (subjectID) {
      const res = await directorysList({ subjectID })
      // console.log(res)
      this.directorys = res.data
    },
    // 企业列表
    async companysList () {
      const res = await companysList()
      // console.log(res)
      this.companys = res.data.items
    },
    // 城市选中后寻找地区
    provincesChange (value) {
      this.citys = citysList(value)
      // console.log(city)
    },
    // 覆盖默认上传的钩子
    httpRequest (file, index) {
      // console.log(file)
      const uploadImg = file.file
      // console.log(index)
      const indexName = uploadImg.name.lastIndexOf('.')
      const ext = uploadImg.name.slice(indexName)

      cos.uploadFile({
        Bucket: 'hmmm-1317544063', /* 填写自己的 bucket，必须字段 */
        Region: 'ap-beijing', /* 存储桶所在地域，必须字段 */
        Key: new Date() + Number.parseInt(Math.random() * 10000000) + Number.parseInt(Math.random() * 10000000) + ext, /* 存储在桶里的对象键（例如:1.jpg，a/b/test.txt，图片.jpg）支持中文，必须字段 */
        Body: uploadImg, // 上传文件对象
        SliceSize: 1024 * 1024 * 5, /* 触发分块上传的阈值，超过5MB使用分块上传，小于5MB使用简单上传。可自行设置，非必须 */
        onProgress: function (progressData) {
          // console.log(JSON.stringify(progressData))
        }
      }, (err, data) => {
        if (err) {
          console.log('上传失败', err)
        } else {
          // console.log('上传成功')
          // console.log(data)
          if (this.form.options[index].img !== '') {
            this.form.options[index].img = this.form.options[index].img + ',' + data.Location
          } else {
            this.form.options[index].img = data.Location
          }
        }
      })
    },
    // 图片上传前的判断
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/gif' || file.type === 'image/bmp'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG PNG GIF BMP  格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    // 文件改变的时候
    onChange (file, fileList, index) {
      this.form.options[index].fileList = fileList
    },
    // 移除图片
    onRemove (file, fileList, index) {
      // console.log(file)
      const indexFile = this.form.options[index].fileList.findIndex(item => item.uid === file.uid)
      console.log(indexFile)
      const flag = this.form.options[index].img.indexOf(',')
      if (flag !== -1) {
        this.form.options[index].img = this.form.options[index].img.split(',').splice(index, 1)
      } else {
        this.form.options[index].img = ''
      }

      console.log(this.form.options[index].img)
    },
    // form表单提交
    submitForm (formName) {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          if (this.$route.query.id) {
            await update(this.form)
            this.$message.success('更新成功！')
          } else {
            await questionsAdd(this.form)
            this.$message.success('新增成功！')
          }
          this.$router.push('/questions/list')
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 增加选项
    addQuestionType () {
      // 增加选项
      this.form.options.push({ isRight: false, code: 'D', title: '', img: '', fileList: [] })
      // 改变 选项code
      this.changeOptions()
    },
    // 重新改变Options
    changeOptions (flag) {
      this.tag = 65
      this.form.options.forEach(item => {
        item.code = String.fromCharCode(this.tag)
        this.tag++
      })

      // 处理url
      if (flag) {
        this.form.options.forEach(item => {
          if (item.img !== '') {
            const arr = item.img.split(',').map(item => {
              return { url: 'http://' + item }
            })

            this.$set(item, 'fileList', arr)
          }
        })
      }
    },
    // 删除选项
    delQuestionType (index) {
      this.form.options.splice(index, 1)
      this.changeOptions()
    },
    // 题型更改选中后
    questionTypeInput () {
      if (this.form.questionType !== '2') {
        this.form.options = newOptions()
      }
    },
    async detailList () {
      console.log(1)
      const res = await detailList({ id: this.$route.query?.id })
      console.log(res)
      this.form = res.data
      this.changeOptions(true)
    }
  }
}
</script>

<style scoped lang='scss'>
.container {
  padding: 20px;
}
.imageText {
  font-size: 14px;
}
::v-deep {
  .ql-editor {
    height: 176px;
  }
  .el-textarea__inner {
    width: 400px;
    height: 100px;
  }
  .el-upload {
    position: relative;
    width: 100px;
    height: 60px;
    line-height: 60px;
  }
  .el-radio {
    margin-right: 10px;
  }
  .icon-close {
    position: absolute;
    right: 0;
    top: 0;
    width: 13px;
    height: 13px;
    transform: translate(50%, -50%);
    background: #fff;
    font-size: 12px;
    color: #999;
    border: 1px solid #999;
    border-radius: 50%;
  }
  .el-upload-list li {
    width: 100px;
    height: 60px;
  }
}
</style>
